import { Injectable } from '@nestjs/common';
import { CreateCategoryDto } from './dto/create-category.dto';
import { UpdateCategoryDto } from './dto/update-category.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Category } from './entities/category.entity';
import { EventStatusEnum, CategoryStatusEnum } from 'src/common/constant/enums';
import logger from 'src/common/utils/log';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(Category)
    private readonly repository: Repository<Category>,
  ) {}
  async create(createCategoryDto: CreateCategoryDto) {
    return await this.repository.save(createCategoryDto);
  }

  async findById(id: number) {
    return await this.repository.findOneBy({ id });
  }

  async findByTournamentId(tournamentId: number) {
    return await this.repository.find({
      where: { tournament: { id: tournamentId } },
    });
  }

  async update(id: number, updateCategoryDto: UpdateCategoryDto) {
    return await this.repository.update(id, updateCategoryDto);
  }

  async remove(id: number) {
    return await this.repository.delete(id);
  }
  async removeInIds(ids: number[]) {
    return await this.repository.delete(ids);
  }
  async removeIds(ids: number[]) {
    return await this.removeInIds(ids);
  }
  async getByIdWithEvents(id: number) {
    return await this.repository.findOne({
      where: { id },
      relations: ['events'],
    });
  }

  async checkFinish(id: number) {
    logger.info('finishCategory...', id);
    const { events } = await this.getByIdWithEvents(id);
    const isAllFinished = events.every(
      (event) => event.status === EventStatusEnum.Finished,
    );
    if (isAllFinished) {
      await this.update(id, {
        status: CategoryStatusEnum.Finished,
      });
    }
    logger.info('finishCategory...', id, isAllFinished);
    return isAllFinished;
  }
}
